<?php

include_once("../info_struct.php");

/*
 * Usage:
 * evaluate_infos(in, refs)
 * Parameters:
 * in - infos object with user input that is to be searched for in the
 *     databases.
 * refs - Infos objects that are returned from the databases.
 * Return:
 * Returns an sorted array with possible matches for the user input.
 * (The first element is the most likely match)
 */
function evaluate_infos($in, $refs) {
    // Contains likely matches for the user input
    $return = array();

    /* Upper bounds for distance between author and title given by user and
     * author and title returned by the database
     */
    $bnd_author = 5;
    $bnd_title = 5;
    
    // Evaluation of each reference returned from external database
    foreach ($refs as $ref) {
        // Levenshtein distance between user title and title from database
        $sample_title = strtolower($in->title);
        $ext_title = strtolower($ref->title);
        $lev_title = levenshtein($sample_title, $ext_title);
        // Levenshtein distance between user author and author from database
        $sample_author = strtolower($in->author);
        $ext_author = strtolower($ref->author);
        $lev_author = levenshtein($sample_author, $ext_author);
        
        // Determining upper bounds for current distances (atleast 5)
        $bnd_title = round(strlen($ref->title) / 5);
        if ($bnd_title < 5) {
            $bnd_title = 5;
        }
        
        $bnd_author = round(strlen($ref->author) / 5);
        if ($bnd_author < 5) {
            $bnd_author = 5;
        }
        
        
        /* Add current ref to return-array if its distance is within the
         * upper bound and its year corresponds to the year specified by the input. 
         * Its rating is added, as well.
         */
        if ($lev_title <= $bnd_title && $ref->year == $in->year) {
            /* Ratio between distance and its upper bound. 
             * Used to sort the return-array.
            */
            $rate = $lev_title/$bnd_title + $lev_author/$bnd_author;
            $ref->rating = $rate;
            array_push($return, $ref);
        }
        
        
    }
    
    /*Sorting the references according to their rating */
    usort($return, "rating_sort");
    
    return $return;
}

/*
 * Usage:
 * rating_sort(a, b);
 * Parameter:
 * a - infos object with rating
 * b - infos object with rating
 * Return:
 * Difference between rating of a and rating of b
 */
function rating_sort($a, $b) {
    return $a->rating - $b->rating;
}


?>